import { InventoryStatus, Product, ProductService, ProductStatus, ProductType } from "@mallfoundry/catalog"
import { PageList } from "@mallfoundry/shared/data"
import { useEffect, useState } from "react"

interface UseProductOptions {
  storeId?: string
  name?: string
  collections?: string[]
  minPrice?: number
  maxPrice?: number
  types?: string | string[] | ProductType | ProductType[]
  statuses?: string | string[] | ProductStatus | ProductStatus[]
  inventoryStatuses?: string | string[] | InventoryStatus | InventoryStatus[]
}

export function useProducts(options: UseProductOptions) {
  const {
    storeId, name, collections, types,
    minPrice, maxPrice, statuses, inventoryStatuses,
  } = options
  const [loading, setLoading] = useState(false)
  const [pageProducts, setPageProducts] = useState(PageList.empty<Product>())

  useEffect(() => {
    const query = ProductService.createProductQuery().toBuilder()
      .storeId(storeId).name(name)
      .minPrice(minPrice).maxPrice(maxPrice)
      .collections(collections)
      .types(types).statuses(statuses)
      .inventoryStatuses(inventoryStatuses)
      .build()
    setLoading(true)
    ProductService.getProducts(query)
      .then(setPageProducts)
      .finally(() => setLoading(false))
  }, [storeId, name, minPrice, maxPrice, collections, types, statuses, inventoryStatuses])

  return {
    loading,
    ...pageProducts,
  }
}

export function useProduct(productId: string) {
  const [loading, setLoading] = useState(false)
  const [product, setProduct] = useState(new Product())

  useEffect(() => {
    setLoading(true)
    ProductService.getProduct(productId)
      .then(setProduct)
      .finally(() => setLoading(false))
  }, [productId])

  return {
    loading,
    product,
  }
}
